using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Comteck.Winforms.Extensions {
  public static class EventExtensions {
    /// <summary>
    /// 移除控件某个事件
    /// </summary>
    /// <param name="control">控件</param>
    /// <param name="eventName">需要移除的控件事件名称eg:EventClick</param>
    public static void RemoveControlEvent(this Control control, string eventName) {
      var fl = typeof(Control).GetField(eventName, BindingFlags.Static | BindingFlags.NonPublic);
      if (fl == null) { return; }

      var obj = fl.GetValue(control);
      if (obj == null) { return; }

      var pi = control.GetType().GetProperty("Events", BindingFlags.NonPublic | BindingFlags.Instance);
      if (pi == null) { return; }

      var eventList = (EventHandlerList)pi.GetValue(control, null);
      eventList?.RemoveHandler(obj, eventList[obj]);
    }
    /// <summary>
    /// 增加控件某个事件
    /// </summary>
    /// <param name="control">控件</param>
    /// <param name="eventName">需要增加的控件事件名称eg:EventClick</param>
    public static void AddControlEvent(this Control control, string eventName) {
      var fl = typeof(Control).GetField(eventName, BindingFlags.Static | BindingFlags.NonPublic);
      if (fl == null) { return; }

      var obj = fl.GetValue(control);
      if (obj == null) { return; }

      var pi = control.GetType().GetProperty("Events", BindingFlags.NonPublic | BindingFlags.Instance);
      if (pi == null) { return; }

      var eventList = (EventHandlerList)pi.GetValue(control, null);
      eventList?.AddHandler(obj, eventList[obj]);
    }
  }
}
